package com.example.asus.happy;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.asus.happy.service.address.Address;
import com.example.asus.happy.service.application.MyApplication;
import com.example.asus.happy.service.finaldata.FinalData;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{
    private String url;//请求地址
    private TextView backTV;//返回
    private EditText userNameET,pwdET;//帐号，密码
    private Button registerBtn;//注册

    //初始化控件
    public void init(){
        backTV = (TextView) findViewById(R.id.backTV);
        userNameET = (EditText) findViewById(R.id.userNameET);
        pwdET = (EditText) findViewById(R.id.pwdET);
        registerBtn = (Button) findViewById(R.id.registerBtn);
    }

    //处理注册的Handler
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    //获取后台数据
                    String response = (String)msg.obj;
                    //response==1,注册成功
                    if (response.equals("1")){
                        Toast.makeText(RegisterActivity.this, FinalData.REGISTER_SUCC, Toast.LENGTH_SHORT).show();
                        finish();
                    }else {
                        Toast.makeText(RegisterActivity.this, FinalData.REGISTER_FAIL, Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    Toast.makeText(RegisterActivity.this, FinalData.NONETWORK, Toast.LENGTH_SHORT).show();
                    break;
            }
        }

    };

    //HttpPostRequest建立连接（）
    private void HttpPostRequest(final String url){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                List<NameValuePair> carteList = new ArrayList<NameValuePair>();
                try{
                    httpPost.setEntity(new UrlEncodedFormEntity(carteList,"UTF-8"));
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    if (httpResponse.getStatusLine().getStatusCode() == 200){
                        HttpEntity httpEntity = httpResponse.getEntity();
                        String count = EntityUtils.toString(httpEntity,"UTF-8");
                        Message message = new Message();
                        message.what = 0;
                        message.obj = count.toString();
                        handler.sendMessage(message);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        //调用初始化方法
        init();
        //返回点击事件
        backTV.setOnClickListener(this);
        //注册安妮
        registerBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.backTV:
                finish();
                break;
            case R.id.registerBtn:
                /**
                 * 注册逻辑
                 * 1.获取用户输入的帐号和密码
                 * 2.提交至后台
                 * 3.根据后台返回结果判断是否注册成功（）
                 * 4.成功：跳转至登录界面，提示用户可以登录了，失败：提示失败原因
                 */
                //获取用户名，密码
                String userName = userNameET.getText().toString();
                String pwd = pwdET.getText().toString();
                //如果用户名或密码为空给出提示
                if (userName.trim().equals("") || pwd.trim().equals("")){
                    Toast.makeText(this, FinalData.NUMBER_PWD_NOTNULL, Toast.LENGTH_SHORT).show();
                }else {
                    //调用注册HttpPostRequest
                    url = Address.ADDRESS+"add?u_userName="+userName+"&u_passWord="+pwd;
                    HttpPostRequest(url);
                }
                break;
        }
    }

    //获取application
    public MyApplication getApp(){
        return (MyApplication) getApplicationContext();
    }
}
